﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//引入命名空间
using stwh_Model;
using stwh_BLL;
using stwh_Common;
using stwh_Common.HttpProc;
using VTemplate.Engine;
using System.Text;
using Newtonsoft.Json;
using System.Reflection;
using System.IO;

namespace stwh_Web.stwh_admin.Common
{
    /// <summary>
    /// 商城模板引擎
    /// </summary>
    public class PageBaseShoppingVT : PageBaseVT
    {
        #region 私有方法
        /// <summary>
        /// 校验会员是否登录
        /// </summary>
        /// <returns></returns>
        private stwh_buyuser ChkLogin()
        {
            //判断是否登录
            stwh_buyuser model = null;
            object qtmodel = HttpContext.Current.Session["shopqtmodel"];
            if (qtmodel != null) model = qtmodel as stwh_buyuser;
            return model;
        }
        #endregion

        public PageBaseShoppingVT(string PageName)
        {
            TpType = TemplateType.Shop;
            string webtemplate = WebSite.LoadWebSite().Webtemplate_s;
            Document = new TemplateDocument(WebClient.GetRootPath() + "/templateshopping/" + webtemplate + "/" + PageName + ".html", Encoding.UTF8);
        }

        /// <summary>
        /// 输出模板内容
        /// </summary>
        public override void OutPutHtml()
        {
            this.Document.Variables.SetValue("shopthis", this);
            base.OutPutHtml();
        }

        #region 扩展方法
        /// <summary>
        /// 判断是否在微信内置浏览器中（true：在微信内置浏览器内。false：不在微信内置浏览器内。）
        /// </summary>
        /// <returns></returns>
        public object ChkWechatBrowser()
        {
            string userAgent = HttpContext.Current.Request.UserAgent;
            if (userAgent != null && (userAgent.Contains("MicroMessenger") || userAgent.Contains("Windows Phone"))) return true;//在微信内部
            else return false;//在微信外部
        }

        /// <summary>
        /// 获取会员购物车数据（会员必须登录，否则无法获取数据）
        /// </summary>
        /// <returns></returns>
        public object GetCartData()
        {
            List<stwh_shopcart> ListData = new List<stwh_shopcart>();
            try
            {
                //判断是否登录
                stwh_buyuser model = ChkLogin();
                if (model != null)
                {
                    ListData = new stwh_shopcartBLL().GetModelList("stwh_buid = " + model.stwh_buid);
                    //计算购物车商品总价格
                    decimal total = 0;
                    int totalcount = 0,jbbz=0;
                    foreach (stwh_shopcart item in ListData)
                    {
                        //不计算库存不足商品的价格
                        if (item.stwh_psumcount != 0) total = (decimal)(item.stwh_sccount * item.stwh_pprice) + total;
                        else jbbz += 1;
                        totalcount = item.stwh_sccount + totalcount;
                    }
                    //判断库存不足商品数量和购物车数量是否一致，如果一致用户不能进行结算操作
                    if (jbbz == ListData.Count) this.Document.Variables.SetValue("IsCartPay", "0");
                    else this.Document.Variables.SetValue("IsCartPay", "1");
                    HttpContext.Current.Session["CartTotalPrice"] = total.ToString("#0.00");//购物车总价
                    HttpContext.Current.Session["CartTotalCount"] = totalcount.ToString();//购物车商品总数
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("获取会员购物车数据出现异常，信息为：" + ex.Message + "\n详细信息为：" + ex.StackTrace);
            }
            return ListData;
        }

        /// <summary>
        /// 获取会员默认收货地址（只有一条数据）（会员必须登录，否则无法获取数据）
        /// </summary>
        /// <returns></returns>
        public object GetAddressDefault()
        {
            stwh_buyaddress modelAdd = new stwh_buyaddress();
            try
            {
                //判断是否登录
                stwh_buyuser model = ChkLogin();
                if (model != null)
                {
                    modelAdd = new stwh_buyaddressBLL().GetModel(model.stwh_buid, 1);
                    modelAdd.stwh_bumobile_h = modelAdd.stwh_bumobile.Substring(0, 3) + "****" + modelAdd.stwh_bumobile.Substring(modelAdd.stwh_bumobile.Length - 4, 4);
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("获取会员默认收货地址出现异常，信息为：" + ex.Message + "\n详细信息为：" + ex.StackTrace);
            }
            return modelAdd;
        }

        /// <summary>
        /// 获取会员收货地址（会员必须登录，否则无法获取数据）
        /// </summary>
        /// <returns></returns>
        public object GetAddressData()
        {
            List<stwh_buyaddress> modelAdd = new List<stwh_buyaddress>();
            try
            {
                //判断是否登录
                stwh_buyuser model = ChkLogin();
                if (model != null)
                {
                    modelAdd = new stwh_buyaddressBLL().GetModelList("stwh_buid = " + model.stwh_buid);
                    for (int i = 0; i < modelAdd.Count; i++)
                    {
                        modelAdd[i].stwh_bumobile_h = modelAdd[i].stwh_bumobile.Substring(0, 3) + "****" + modelAdd[i].stwh_bumobile.Substring(modelAdd[i].stwh_bumobile.Length - 4, 4);
                    }
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("获取会员收货地址出现异常，信息为：" + ex.Message + "\n详细信息为：" + ex.StackTrace);
            }
            return modelAdd;
        }

        /// <summary>
        /// 根据地址ID获取会员的地址（会员必须登录，否则无法获取数据）
        /// </summary>
        /// <returns></returns>
        public object GetAddressIDData()
        {
            stwh_buyaddress modeladdress = new stwh_buyaddress();
            try
            {
                string id = HttpContext.Current.Request["id"];
                if (PageValidate.IsNumber(id))
                {
                    //判断是否登录
                    stwh_buyuser model = ChkLogin();
                    if (model != null)
                    {
                        List<stwh_buyaddress> datalist = new stwh_buyaddressBLL().GetModelList("stwh_buid = " + model.stwh_buid + " and stwh_baid = " + id);
                        if (datalist.Count != 0) modeladdress = datalist[0];
                    }
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("根据地址ID获取会员的地址出现异常，信息为：" + ex.Message + "\n详细信息为：" + ex.StackTrace);
            }
            return modeladdress;
        }

        /// <summary>
        /// 获取会员最新订单总价或获取具体订单的总价（会员必须登录，否则无法获取数据）
        /// </summary>
        /// <returns></returns>
        public object GetOrderTotalPrice()
        {
            decimal sumprice = 0;
            try
            {
                //判断是否登录
                stwh_buyuser model = ChkLogin();
                if (model != null)
                {
                    string orderid = HttpContext.Current.Request["orderid"];
                    if (!string.IsNullOrEmpty(orderid))
                    {
                        if (PageValidate.IsCustom(@"^\d{16,}$", orderid)) sumprice = new stwh_orderBLL().GetOrderTotalPrice(orderid);
                    }
                    else
                    {
                        string stwh_orddid = "";//订单编号
                        sumprice = new stwh_orderBLL().GetOrderTotalPrice(model.stwh_buid, ref stwh_orddid);
                    }

                    //如果有其他规则，sumprice加上其它规则价格

                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("获取会员最新订单总价或获取具体订单的总价出现异常，信息为：" + ex.Message + "\n详细信息为：" + ex.StackTrace);
            }
            return sumprice;
        }

        /// <summary>
        /// 获取会员的订单和订单详细（只获取第一页10条数据，会员必须登录，否则无法获取数据）
        /// </summary>
        /// <returns></returns>
        public object GetOrderUser()
        {
            List<stwh_order> orderdatalist = new List<stwh_order>();
            try
            {
                //判断是否登录
                stwh_buyuser model = ChkLogin();
                if (model != null)
                {
                    List<stwh_orderdetails> datalist = new List<stwh_orderdetails>();
                    //获取订单号，如果存在
                    string orderid = HttpContext.Current.Request["orderid"];
                    string where = "stwh_buid=" + model.stwh_buid;
                    if (!string.IsNullOrEmpty(orderid))
                    {
                        if (PageValidate.IsCustom(@"^\d{16,}$", orderid)) where = where + " and stwh_orddid = '" + orderid + "'";
                    }
                    List<stwh_order> jblist = new stwh_orderBLL().GetOrder(where, 10, 0, ref datalist);
                    for (int i = 0; i < jblist.Count; i++)
                    {
                        jblist[i].stwh_ortel_sub = jblist[i].stwh_ortel.Substring(0, 3) + "****" + jblist[i].stwh_ortel.Substring(jblist[i].stwh_ortel.Length - 4, 4);
                        orderdatalist.Add(jblist[i]);
                    }
                    this.Document.Variables.SetValue("OrderDetailsList", datalist);
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("获取会员的订单和订单详细出现异常，信息为：" + ex.Message + "\n详细信息为：" + ex.StackTrace);
            }
            return orderdatalist;
        }
        #endregion
    }
}